//
//  SearchViewController.m
//  IconMaster
//
//  Created by mac on 2017/7/28.
//  Copyright © 2017年 yangweiwei. All rights reserved.
//

#import "SearchViewController.h"
#import "SearchTableViewCell.h"
#import "SearchHeaderView.h"
#import "HomeThemeVC.h"
@interface SearchViewController ()<UITableViewDataSource, UITableViewDelegate,SearchHeaderViewDelegate, UISearchBarDelegate>{
    NSArray *hot_arr;   //热门搜索的数组
    int hight;
    int Totalhight;
    int   hight0;
}
@property (weak, nonatomic) IBOutlet UIView *NavSearch;
@property (nonatomic, strong) UIButton *searchButton;
@property (nonatomic, strong) NSMutableArray *historyArr;
@property (nonatomic, strong) UITableView *tableView0;
@property (nonatomic, strong) NSString *searchString;
@property (nonatomic, strong) NSMutableArray *searchArr;
@end

@implementation SearchViewController
- (NSMutableArray *)searchArr{

    if (!_searchArr) {
        _searchArr = [NSMutableArray array];
    }
    return _searchArr;
}
- (NSMutableArray *)historyArr{
    
    if (!_historyArr) {
        _historyArr = [NSMutableArray array];
    }
    return _historyArr;
}
- (void)searchHotData{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [IconmasterHttp GreatNetWorkingRequestType:GreatRequestType_GET andurl:SearchHot andparameters:nil andcomplete:^(id json, NSError *error) {
        if ([json[@"code"] integerValue] == 200) {
            hot_arr = json[@"data"][@"list"][@"content"];
            [self.tableView0 reloadData];
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }
    }];
}
- (void)searchData{
   [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [IconmasterHttp GreatNetWorkingRequestType:GreatRequestType_GET andurl:SearchURL andparameters:@{@"keyword":self.searchString} andcomplete:^(id json, NSError *error) {
        if ([json[@"code"] integerValue] == 200) {
            //se [self alterAction:@""];
            NSArray *arr =  json[@"data"][@"list"][@"content"];
            if (arr.count == 0) {
                [self alterAction:NSLocalizedString(@"正在添加该内容,请期待！", nil)];
            }else{
                 NSArray *arr = json[@"data"][@"list"][@"content"];
                for (int i = 0; i < arr.count; i++) {
                    
                    if ([arr[i][@"albunIsVisable"] integerValue]) {
                        HomeModel *homeModel = [[HomeModel alloc] initWithDict:[HomeModel setDictModel:arr[i]]];
                        [self.searchArr addObject:homeModel];
                    } 
                }

//                self.searchArr = json[@"data"][@"list"][@"content"];
                HomeThemeVC *themeVc = [[HomeThemeVC alloc] init];
                themeVc.themeArr = self.searchArr;
                [self.searchArr removeAllObjects];
                themeVc.nameStr = DataWithZHOrEn(arr[0][@"chineseName"], arr[0][@"englishName"]) ;
                
                [self.navigationController pushViewController:themeVc animated:YES];
                
            }
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }else{
            
        }
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setImageViewINNav];
//    self.automaticallyAdjustsScrollViewInsets = NO;
    [self setBarType];
    [self searchHotData];
//    hot_arr = @[@"大概",@"无知",@"风云变幻",@"施耐庵",@"唉",@"西门吹雪",@"呵呵哒",@"快看看",@"窿窿啦啦",@"一杆禽兽狙",@"合欢花",@"暴走大事件",@"非诚勿扰",@"呵呵呵", @"极限跳找", @"星光大道", @"黄金一百秒", @"开门大吉", @"了不起的挑战", @"NBA"];;
    self.historyArr = [[NSUserDefaults standardUserDefaults] mutableArrayValueForKey: @"infoArr"];
    self.NavSearch.sd_layout.leftSpaceToView(self.navigationItem.leftBarButtonItem, 0).rightSpaceToView(self.navigationItem.rightBarButtonItem, 0);
    [self CreatTableView_];
    // Do any additional setup after loading the view.
}
- (void)CreatTableView_{
    
    self.tableView0 = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, KWidth, KHeight - 64) style:UITableViewStyleGrouped];
     
    self.tableView0.delegate = self;
    self.tableView0.dataSource = self;
    self.tableView0.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView0];
//    self.tableView0.sd_layout.topSpaceToView(self.navigationItem, 0);
}
#pragma mark --tableView的代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 0;
    }
    return self.historyArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    //    NSInteger section = indexPath.section;
    //    NSInteger row = indexPath.row;
    if (indexPath.section ==1) {
        static NSString *identifier = @"search";
        SearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell = [[NSBundle mainBundle] loadNibNamed:@"Search" owner:self options:nil][0];
        }
        cell.sousuolishiLab.text = self.historyArr[indexPath.row];
        //    cell.accessoryType = UITableViewCellAccessoryNone;
        return cell;
    }
    return nil;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        return 30;
    }
    return [self backHeaderHigh];
}
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    
//    return 60;
//}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    self.searchString = self.historyArr[indexPath.row];
    [self searchData];
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section ==0) {
        SearchHeaderView *headerView = [[SearchHeaderView alloc] initWithReuseIdentifier:@"searchheader" andArr:hot_arr];
        headerView.delegate = self;
        return headerView;
    }else{
    
        UIView *view0 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KWidth - 16, 50)];
         
        UIImageView *imageView0 = [[UIImageView alloc] initWithFrame:CGRectMake(8, 10, 30, 30)];
//        imageView0.backgroundColor = [UIColor whiteColor];
        imageView0.image = [UIImage imageNamed:@"historicalrecord"];
       
        [view0 addSubview:imageView0];
        [imageView0 sizeToFit];
        UILabel *titleLab = [[UILabel alloc] init];
        titleLab.text = NSLocalizedString(@"历史记录", nil);
        titleLab.textColor = [UIColor grayColor];
        [view0 addSubview:titleLab];
        imageView0.sd_layout.centerYEqualToView(titleLab);
        titleLab.sd_layout.leftSpaceToView(imageView0, 8).topSpaceToView(view0, 0).heightIs(30).widthIs(120);
        
        UIButton *clearButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [clearButton setImage:[UIImage imageNamed:@""] forState:Normal];
        [clearButton setTitle:NSLocalizedString(@"清除历史记录", nil) forState:Normal];
        [clearButton addTarget:self action:@selector(clearButton) forControlEvents:TouchUPInside];
        [view0 addSubview:clearButton];
        clearButton.sd_layout.rightSpaceToView(view0, 8).topSpaceToView(view0, 0).heightIs(30).widthIs(120);
        return view0;
    }
    return nil;
}
- (void)clearButton{

    [self.historyArr removeAllObjects];
    NSUserDefaults*userDefaults = [NSUserDefaults  standardUserDefaults];
    [userDefaults removeObjectForKey:@"infoArr"];
    [userDefaults   synchronize];
    [self.tableView0 reloadData];
}
-(void)clickSearchButton:(UIButton *)sender{

//    NSLog(@"%@", sender.titleLabel.text);
    [self nsuserSaveArr:sender.titleLabel.text];
    self.searchString = sender.titleLabel.text;
    [self searchData];
}
- (NSUInteger)backHeaderHigh{

    CGFloat w = 0;//保存前一个button的宽以及前一个button距离屏幕边缘的距离
    CGFloat h = 0;//用来控制button距离父视图的高
    for (int i = 0; i < hot_arr.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.tag = 100 + i;
        button.layer.borderColor = [[UIColor grayColor] CGColor];
        button.layer.borderWidth = 1;
        //        button.backgroundColor = [UIColor greenColor];
        [button addTarget:self action:@selector(handleClick:) forControlEvents:UIControlEventTouchUpInside];
        [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        //根据计算文字的大小
        
        NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:12]};
        CGFloat length = [hot_arr[i][@"keyword"] boundingRectWithSize:CGSizeMake(KWidth, 2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.width;
        //为button赋值
        [button setTitle:hot_arr[i] forState:UIControlStateNormal];
        //设置button的frame
        button.frame = CGRectMake(20 + w, h, length + 15 + 10 , 30);
        //当button的位置超出屏幕边缘时换行 320 只是button所在父视图的宽度
        if(20 + w + length + 15 + 10 > KWidth){
            w = 0; //换行时将w置为0
            h = h + button.frame.size.height + 10;//距离父视图也变化
            button.frame = CGRectMake(20 + w, h, length + 15 + 10, 30);//重设button的frame
        }
        w = button.frame.size.width + button.frame.origin.x;
//        [self.view addSubview:button];
    }
    return h+100;
}
//点击事件
- (void)handleClick:(UIButton *)sender{
       UIButton *clickedBtn = sender;
//    self.searchBar.text = clickedBtn.titleLabel.text;
//    //    [_historyArr addObject:clickedBtn.titleLabel.text];
//    //    [self wlk:clickedBtn.titleLabel.text];
//    [self creatHiatoryArrPlist:clickedBtn.titleLabel.text];
//    //    SearchDetailVC *searchDatial = [[SearchDetailVC alloc] init];
//    [DataModel object].serachKey_word = self.searchBar.text;
//    NSLog(@"---historyArr==%@", _historyArr);
//    [self.navigationController pushViewController:[SearchDetailVC new] animated:YES];
    NSLog(@"-----点击的按钮 %@",  clickedBtn.titleLabel.text);
    [self showAdmobInController:self];
    [self nsuserSaveArr:clickedBtn.titleLabel.text];
    //    NSLog(@"%@", button.titleLabel.text);
}
// UISearchBarDelegate定义的方法，用户单击虚拟键盘上Search按键时激发该方法  
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar  
{  
    NSLog(@"----searchBarSearchButtonClicked------");  
    // 调用filterBySubstring:方法执行搜索  
//    [self filterBySubstring:searchBar.text];  
    // 放弃作为第一个响应者，关闭键盘  
    [searchBar resignFirstResponder];  
    self.searchString = searchBar.text;
    [self searchData];
//    [self.historyArr addObject:searchBar.text];
    [self nsuserSaveArr:searchBar.text];
    [self.tableView0 reloadData];
}  
- (void)nsuserSaveArr:(NSString *)string{

    NSMutableArray *infoArr = [[NSUserDefaults standardUserDefaults] mutableArrayValueForKey:@"infoArr"];
    NSMutableArray *mutableCopyArr = [NSMutableArray array];
    if (infoArr.count == 0) {
        //
    }else{
      mutableCopyArr = [infoArr mutableCopy];
    }
     
    
    [mutableCopyArr addObject: string];
    
    [[NSUserDefaults standardUserDefaults] setObject: mutableCopyArr forKey:@"infoArr"];
    
    [[NSUserDefaults standardUserDefaults] synchronize];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
